//
//  KFDChooseTeacherViewController.m
//  KFD
//
//  Created by JIRENTIANXIANG on 7/9/15.
//  Copyright © 2015 kfd. All rights reserved.
//

#import "KFDChooseTeacherViewController.h"
#import "KFDUIConfigurator.h"
#import "KFDChooseTeacherViewModel.h"
#import <MJRefresh/MJRefresh.h>
#import "KFDChooseTeacherViewCell.h"
#import "KFDTeacherIntroViewComposer.h"
#import "KFDClient.h"
#import "JTToast.h"
#import "KFDTeachingViewController.h"

#define KFDChooseTeacherViewCellReuseIdentifier @"KFDChooseTeacherViewCell"
#define KFDChooseTeacherViewCellNibName @"KFDChooseTeacherViewCell"

@interface KFDChooseTeacherViewController ()

@property (strong,nonatomic) KFDChooseTeacherViewModel* viewModel;

@end

@implementation KFDChooseTeacherViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    KFDUIConfigurator* uiConfigurator=[KFDUIConfigurator configuratorForViewController:self];
    [uiConfigurator configureNavigationBarWithBackAction:@selector(goBack)];
    self.title=@"选择老师";
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTableview) name:KFDTeachersReadyNotification object:nil];
    self.viewModel=[[KFDChooseTeacherViewModel alloc] init];
    [self.viewModel loadTeachersWithMaxCount:10];
    __weak typeof(self) weakSelf=self;
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf.viewModel loadTeachersWithMaxCount:weakSelf.viewModel.teachers.count];
    }];
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf.viewModel loadTeachersWithMaxCount:weakSelf.viewModel.teachers.count+5];
    }];
}

-(void)refreshTableview
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
        if (self.tableView.header.isRefreshing) {
            [self.tableView.header endRefreshing];
        }
        if (self.tableView.footer.isRefreshing) {
            [self.tableView.footer endRefreshing];
        }
    });
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KFDTeachersReadyNotification object:nil];
}

-(void)goBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.viewModel.teachers.count;
}

-(CGFloat)tableView:(nonnull UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    KFDTeacherIntroViewComposer* composer=[[KFDTeacherIntroViewComposer alloc] init];
    composer.teacher=self.viewModel.teachers[indexPath.row];
    return [composer layout]+48;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KFDChooseTeacherViewCell *cell = [tableView dequeueReusableCellWithIdentifier:KFDChooseTeacherViewCellReuseIdentifier];
    if (!cell) {
        cell=[[NSBundle mainBundle] loadNibNamed:KFDChooseTeacherViewCellNibName owner:nil options:nil].firstObject;
    }
    cell.teacher=self.viewModel.teachers[indexPath.row];
    return cell;
}

//-------------------------------------------------------------------------
// Table view delegate
//-------------------------------------------------------------------------
-(void)tableView:(nonnull UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    KFDTeacher* teacher=self.viewModel.teachers[indexPath.row];
    if (teacher.ischoose) {
        KFDTeachingViewController* teachingVC=[[KFDTeachingViewController alloc] init];
        teachingVC.teacher=self.viewModel.teachers[indexPath.row];
        [self.navigationController pushViewController:teachingVC animated:YES];
    }else{
        UIAlertController* alertController=[UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"确定要选择%@老师作为你的指导老师吗？一周只有一次选择机会",teacher.realname] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction* cancelAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
        UIAlertAction* confirmAction=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * __nonnull action) {
            KFDClient* client=[KFDClient sharedClient];
            [client chooseTeacher:teacher.id successHandler:^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.tableView reloadData];
                });
            } failureHandler:^(KFDResponseBody *response) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[JTToast makeText:response.message] showInView:self.view size:CGSizeMake(response.message.length*20, 40)];
                });
            }];
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:confirmAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}
//-------------------------------------------------------------------------

@end
